<template>
  <continer
    :showPage="showPage"
    :shadow="true"
    :pageshadow="true"
    :isNoTabs="true"
  >
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="handleSearchFun"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="handleSearchFun"
        >查询</el-button
      >
      <el-button
        size="mini"
        @click="addBtnFun"
        v-functions="['spare_mgt_category_insert']"
        >新建</el-button
      >
    </template>
    <template slot="content">
      <!-- 表格 -->
      <instiutionTable
        ref="tableRef"
        @currentChange="currentChangeFun"
        @sizeChange="sizeChange"
        :pages="spareTablePages"
        :instiutionTableData="spareTableData"
        :instiutionTableHeader="spareTableHeader"
      >
        <template #typeName="{ scope }">
          {{ scope.row.typeId | filterTypeName }}
        </template>
        <template #unitName="{ scope }">
          {{ allUnitObj[scope.row.unitId] ? allUnitObj[scope.row.unitId].typeName : '' }}
        </template>
      </instiutionTable>
    </template>
    <template slot="page">
      <addOrEditOrDetailSpare
        ref="spareParts"
        :showStatus="showStatus"
        :titleArr="titleArr"
        @pageBack="returnPage"
        @cancelFun="returnPage"
        @handleSaveFun="handleSaveFun"
      />
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref, Mixins } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import drawer from '@/common/views/drawer/index.vue'
import addOrEditOrDetailSpare from '@/afterSales/views/spare/commodityCode/addOrEditOrDetailSpare.vue'
import { commonAction, deepClone } from '@/utils/common'
import { state, mutations } from '../store/spareData'
import { checkPermission } from '@/utils/directive'
import filterTypeName from '../mixins/filterTypeName'
@Component({
  name: 'CommodityCode',
  components: {
    QuickSearch,
    continer,
    instiutionTable,
    drawer,
    addOrEditOrDetailSpare
  }
})
export default class Category extends Mixins(filterTypeName) {
  @Ref() private readonly spareParts!: addOrEditOrDetailSpare
  private $confirm: any
  private $message: any

  private $afterSalesGetCache: any
  private $getCache: any

  private showPage: boolean = false

  private spareTableData = [] // 表格数据

  private spareTableHeader: any[] = [ // 表头
    { label: '备件编号', prop: 'spareNumber' },
    { label: '备件名称', prop: 'name' },
    { label: '类型', prop: 'typeName', custom: true },
    { label: '型号', prop: 'model' },
    { label: '单位', prop: 'unitName', custom: true },
    { label: '销售价', prop: 'price' }
  ]

  private showStatus: string = '' // 编辑edti 新增add

  private spareTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 100
  }

  private quickSearchForm: any = {
    form: {
      spareNumber: '',
      spareName: '',
      spareTypeIds: [],
      spareModel: '',
      priceStart: undefined,
      priceEnd: undefined
    },
    advSearchOptions: [
      { label: '备件编号', inputType: 'input', placeholder: '请输入', name: 'spareNumber', clearable: true },
      { label: '备件名称', inputType: 'input', placeholder: '请输入', name: 'spareName', clearable: true },
      { label: '类型', inputType: 'cascader', placeholder: '请输入', name: 'spareTypeIds', clearable: true, props: { value: 'id', label: 'typeName', children: 'children', expandTrigger: 'hover', checkStrictly: false, emitPath: false }, options: state.spareTypeList },
      { label: '型号', inputType: 'input', placeholder: '请输入', name: 'spareModel', clearable: true },
      { label: '销售价', inputType: 'numberRange', placeholder: '请输入', preName: 'priceStart', afterName: 'priceEnd', clearable: true }
    ]
  } // 快捷检索数据

  private titleArr: any[] = []

  private formateOptions (val) {
    if (val) {
      val.forEach(item => {
        if (item.children) {
          item.children = this.formateOptions(item.children)
        }
      })
      const arr = val.filter(item => item.isDelete === 0)
      if (arr.length) {
        return arr
      } else {
        return null
      }
    }
  }

  private handleSearchFun () { // 搜素
    this.spareTablePages.current = 1
    this.getTableList()
  }

  private get allSpareTypeObj () {
    return state.allSpareTypeObj
  }

  private get allUnitObj () {
    return state.allUnitObj
  }

  private getTableList () { // 获取表格数据
    const { spareModel, spareTypeIds, spareName, priceStart, priceEnd, spareNumber } = this.quickSearchForm.form
    const spareTypeIdsFormat = spareTypeIds && spareTypeIds.length ? [spareTypeIds.join()] : []
    const sedData = {
      limit: this.spareTablePages.pageSize,
      page: this.spareTablePages.current,
      spareModel,
      spareNumber,
      spareTypeIds: spareTypeIdsFormat,
      spareName,
      priceStart,
      priceEnd
    }
    commonAction({
      url: '/server-work/action/spare/list',
      method: 'post',
      data: sedData
    }).then(res => {
      if (res.success) {
        this.spareTableData = res.data.list
        this.spareTablePages.total = res.data.count
      }
    })
  }

  private currentChangeFun (page: number) { // 翻页
    this.spareTablePages.current = page
    this.getTableList()
  }

  private sizeChange (size: number) {
    this.spareTablePages.pageSize = size
    this.getTableList()
  }

  private addBtnFun () { // 新增
    this.showStatus = 'add'
    this.showPage = true
    this.titleArr = ['新建备件品类']
    this.$nextTick(() => {
      this.spareParts.accessForm = { // 清空数据
        spareNumber: '',
        id: '',
        name: '',
        typeId: '',
        model: '',
        unitId: '',
        price: undefined,
        description: '',
        attach: []
      }
      this.spareParts.fileList = []
    })
  }

  private editFun (row: any) { // 编辑
    this.showStatus = 'edit'
    this.showPage = true
    this.titleArr = ['编辑备件品类']
    this.$nextTick(() => {
      this.spareParts.accessForm = deepClone(row)
      this.spareParts.accessForm.typeId = row.typeId.split(',')
      if (row.attach) {
        this.spareParts.fileList = deepClone(row.attach)
      }
    })
  }

  private handleDel (row: any) { // 删除
    this.$confirm('删除此品类可能会影响相关信息的展示，确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commonAction({
        url: '/server-work/action/spare/delete',
        method: 'post',
        data: { id: row.id }
      }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.getTableList()
        }
      })
    })
  }

  private handleSaveFun () { // 新建保存
    this.showPage = false
    this.getTableList()
  }

  private returnPage () { // 新增返回列表
    this.showPage = false
  }

  private get isStoreEmpty () {
    return state.spareTypeList.length === 0 || state.spareOutStockTypeList.length === 0 || state.spareInStockTypeList.length === 0 || state.unitList.length === 0
  }

  private activated () {
    if (this.isStoreEmpty) {
      commonAction({
        url: '/server-work/action/spareConfig/list',
        method: 'get'
      }).then(res => {
        mutations.setStateData('arr', 'spareTypeList', this.formateOptions(res.data.spareTypeList) || [])
        mutations.setStateData('arr', 'spareOutStockTypeList', res.data.spareOutStockTypeList)
        mutations.setStateData('arr', 'spareInStockTypeList', res.data.spareInStockTypeList)
        mutations.setStateData('arr', 'unitList', res.data.unitConfig)
        this.quickSearchForm.advSearchOptions[2].options = state.spareTypeList
      })
    } else {
      this.quickSearchForm.advSearchOptions[2].options = state.spareTypeList
    }
  }

  private mounted () {
    let handlers: any[] = []
    if (checkPermission(null, { value: ['spare_mgt_category_edit'] })) {
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.editFun(scope.row) })
    }
    if (checkPermission(null, { value: ['spare_mgt_category_delete'] })) {
      handlers = [...handlers, ...[{ className: 'danger', name: '删除', handleFn: (scope: any) => this.handleDel(scope.row) }]
      ]
    };
    this.spareTableHeader.push({ label: '操作', width: 100, handlers })
    this.getTableList()
  }
}
</script>
<style lang="stylus" scoped>
>>> .el-input-number
  .el-input__inner
    text-align left
</style>
